<template>
  <div class="admin-articles">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>文章管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddArticle">新增文章</el-button>
          </div>
        </div>
      </template>
      
      <div class="table-toolbar">
        <el-form :inline="true" class="search-form">
          <el-form-item>
            <el-input
              v-model="searchQuery"
              placeholder="搜索标题/内容"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="categoryFilter" placeholder="分类" clearable>
              <el-option 
                v-for="item in categoryOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="statusFilter" placeholder="状态" clearable>
              <el-option label="已发布" value="PUBLISHED" />
              <el-option label="草稿" value="DRAFT" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="visitCount" label="浏览量" width="100" sortable />
        <el-table-column prop="replyCount" label="评论数" width="100" sortable />
        <el-table-column prop="likeCount" label="点赞数" width="100" sortable />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 'PUBLISHED' ? 'success' : 'info'"
            >
              {{ 
                scope.row.status === 'PUBLISHED' ? '已发布' : '草稿'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import api from '@/api'

export default {
  name: 'AdminArticles',
  
  setup() {
    const router = useRouter()
    
    // 表格数据和加载状态
    const tableData = ref([])
    const loading = ref(true)
    
    // 分页参数
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索过滤条件
    const searchQuery = ref('')
    const categoryFilter = ref('')
    const statusFilter = ref('')
    
    // 分类选项
    const categoryOptions = ref([
      { value: 'technology', label: '技术' },
      { value: 'design', label: '设计' },
      { value: 'business', label: '商业' },
      { value: 'lifestyle', label: '生活方式' },
      { value: 'other', label: '其他' }
    ])
    
    // 获取文章列表
    const fetchArticles = async () => {
      loading.value = true
      try {
        // 构建请求参数
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          keyword: searchQuery.value,
          category: categoryFilter.value,
          status: statusFilter.value
        }
        
        // 调用API获取文章列表
        const response = await api.admin.getArticleList(params)
        
        if (response && response.code === 0 && response.data) {
          console.log('获取到文章列表:', response.data)
          
          // 根据后端返回的实际格式处理数据
          if (Array.isArray(response.data)) {
            // 如果后端直接返回数组
            tableData.value = response.data
            total.value = response.data.length
          } else if (response.data.list && Array.isArray(response.data.list)) {
            // 如果后端返回分页格式 {list: [...], total: n}
            tableData.value = response.data.list
            total.value = response.data.total || response.data.list.length
          } else {
            // 可能后端直接返回了文章列表数据
            tableData.value = response.data
            total.value = response.data.length || 0
          }
        } else {
          tableData.value = []
          total.value = 0
          ElMessage.warning(response?.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取文章列表失败:', error)
        tableData.value = []
        total.value = 0
        ElMessage.error('获取文章列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索处理
    const handleSearch = () => {
      currentPage.value = 1
      fetchArticles()
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchQuery.value = ''
      categoryFilter.value = ''
      statusFilter.value = ''
      currentPage.value = 1
      fetchArticles()
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchArticles()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchArticles()
    }
    
    // 查看文章
    const handleView = (row) => {
      router.push({ name: 'ArticleDetail', params: { id: row.id } })
    }
    
    // 新增文章
    const handleAddArticle = () => {
      router.push({ name: 'ArticleCreate' })
    }
    
    // 编辑文章
    const handleEdit = (row) => {
      router.push({ name: 'ArticleEdit', params: { id: row.id } })
    }
    
    // 删除文章
    const handleDelete = (row) => {
      ElMessageBox.confirm('删除文章将无法恢复，是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.admin.deleteArticle(row.id)
          ElMessage.success('删除成功')
          fetchArticles() // 刷新列表
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {})
    }
    
    onMounted(() => {
      fetchArticles()
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      searchQuery,
      categoryFilter,
      statusFilter,
      categoryOptions,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleAddArticle,
      handleEdit,
      handleDelete
    }
  }
}
</script>

<style scoped>
.admin-articles {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
}

.table-toolbar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 